package com.tc.excel.handler;

import com.tc.excel.JxlExcelUtils;
import com.tc.excel.anno.ResponseExcel;
import org.springframework.core.MethodParameter;
import org.springframework.core.ResolvableType;
import org.springframework.util.Assert;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Auther: tianchao
 * @Date: 2025/2/15 09:40
 * @Description:
 */
public class ExcelReturnValueHandler implements HandlerMethodReturnValueHandler {

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        System.out.println(returnType.getParameterType());
        return returnType.getMethodAnnotation(ResponseExcel.class)!=null && ResolvableType.forMethodParameter(returnType).resolve()==List.class;
    }

    /**
     * Handle the given return value by adding attributes to the model and
     * setting a view or setting the
     * {@link ModelAndViewContainer#setRequestHandled} flag to {@code true}
     * to indicate the response has been handled directly.
     *
     * @param returnValue  the value returned from the handler method
     * @param returnType   the type of the return value. This type must have
     *                     previously been passed to {@link #supportsReturnType} which must
     *                     have returned {@code true}.
     * @param mavContainer the ModelAndViewContainer for the current request
     * @param webRequest   the current request
     * @throws Exception if the return value handling results in an error
     */
    @Override
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        HttpServletResponse response =  webRequest.getNativeResponse(HttpServletResponse.class);
        Assert.notNull(response,"Excel导出httpServletResponse不能为空");
        ResponseExcel responseExcel = returnType.getMethodAnnotation(ResponseExcel.class);
        Assert.notNull(responseExcel,"Excel导出responseExcel不能为空");
        // 设置请求已经被处理，目的是以免被视图解析器错误的解析
        mavContainer.setRequestHandled(true);
        Class<?> headClass = ResolvableType.forMethodParameter(returnType).getGeneric(0).resolve();
        JxlExcelUtils.exportFileToResponses(
                (List) returnValue,
                responseExcel,
                headClass,
                response
        );
    }
}
